/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.view;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collection;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.model.ContactSheetListItem;
import au.com.lastweekend.jim.model.ContactSheetListModel;
import au.com.lastweekend.jim.swing.SwingUtil;

/**
 * @author <a href="mailto:grant@lastweekend.com.au"> <Grant Gardner> </a>
 * @version $Id: ContactSheet.java,v 1.7 2006/02/19 06:04:55 ggardner Exp $
 */
@SuppressWarnings("serial")
public class ContactSheet extends JScrollPane {

    private static final Logger LOG = Logger.getLogger(ContactSheet.class);

    private class ViewTracksWidthAdapter extends ComponentAdapter implements ListDataListener {

        /**
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
         */
        @Override
        public void componentResized(ComponentEvent event) {

            JViewport viewport = (JViewport) event.getComponent();
            setRowsFromWidth(viewport);
        }

        public void contentsChanged(ListDataEvent e) {

            // Don't care

        }

        public void intervalAdded(ListDataEvent e) {

            setRowsFromWidth();

        }

        public void intervalRemoved(ListDataEvent e) {

            setRowsFromWidth();

        }

    }

    private void setRowsFromWidth() {

        setRowsFromWidth(getViewport());
    }

    private void setRowsFromWidth(final JViewport viewport) {

        Dimension viewportSize = viewport.getSize();
        Component viewComponent = viewport.getView();

        JList view = (JList) viewComponent;
        int newWidth = viewportSize.width;

        if (newWidth > 0) {
            int colsPerRow = newWidth / view.getFixedCellWidth();
            if (colsPerRow > 0) {
                int listSize = view.getModel().getSize();
                int rows = listSize / colsPerRow;
                if (listSize % colsPerRow > 0) {
                    rows++;
                }
                view.setVisibleRowCount(rows);
            }
        }

    }

    public ContactSheet(ContactSheetListModel model) {

        JList view = new JList() {

            @Override
            public boolean getScrollableTracksViewportWidth() { // NOPMD - overriding a Swing method

                return true;
            }

        };

        view.setCellRenderer(new ImageCellRenderer());
        view.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        view.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        this.setViewportView(view);
        ViewTracksWidthAdapter viewTracksWidthAdapter = new ViewTracksWidthAdapter();

        this.getViewport().addComponentListener(viewTracksWidthAdapter);
        model.addListDataListener(viewTracksWidthAdapter);

        bindKeyActions(view);

        getViewList().setModel(model);
        setRowsFromWidth(getViewport());

    }

    private void bindKeyActions(JList view) {

        /* Allow wrapping for normal next/previous */
        Action action = new AbstractAction("selectNextColumn") {

            public void actionPerformed(ActionEvent event) {

                JList list = (JList) event.getSource();
                int leadIndex = list.getLeadSelectionIndex() + 1;
                if (leadIndex < list.getModel().getSize()) {
                    list.setSelectedIndex(leadIndex);
                    list.ensureIndexIsVisible(leadIndex);
                }

            }
        };

        SwingUtil.bindKeyAction(view, action);

        action = new AbstractAction("selectPreviousColumn") {

            public void actionPerformed(ActionEvent event) {

                JList list = (JList) event.getSource();
                int leadIndex = list.getAnchorSelectionIndex() - 1;
                if (leadIndex >= 0) {
                    list.setSelectedIndex(leadIndex);
                    list.ensureIndexIsVisible(leadIndex);
                }

            }
        };

        SwingUtil.bindKeyAction(view, action);

        SwingUtil.debugActionMap(view, LOG);
    }

    /**
     * Public so controllers c
     * 
     * @return
     */
    public JList getViewList() {

        return (JList) this.getViewport().getView();
    }

    public ContactSheetListModel getModel() {

        return (ContactSheetListModel) getViewList().getModel();
    }

    public Collection<ContactSheetListItem> getSelectedItems() {

        Object[] values = getViewList().getSelectedValues();
        Collection<ContactSheetListItem> result = new ArrayList<ContactSheetListItem>(values.length);
        for (Object item : values) {
            ContactSheetListItem listItem = (ContactSheetListItem) item;
            result.add(listItem);
        }

        return result;
    }

    public ContactSheetListItem getSelectedItem() {

        return (ContactSheetListItem) getViewList().getSelectedValue();
    }

    /**
     * Select all (includes folders
     * 
     */
    public void selectAll() {

        getViewList().setSelectionInterval(0, getViewList().getModel().getSize() - 1);

    }

    public void setSlideCellSize(int newSize) {

        JList viewList = getViewList();
        viewList.setFixedCellHeight(newSize);
        viewList.setFixedCellWidth(newSize);
        setRowsFromWidth(getViewport());
    }

    public void addPopupListener(MouseListener popupListener) {

        addMouseListener(popupListener);
        getViewList().addMouseListener(popupListener);
    }

}